#!/usr/bin/python

# Copyright (c) 2013 Matthias S. Benkmann
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this file (originally named snb2txt) and associated documentation files 
# (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is furnished
# to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. 


from __future__ import with_statement, division, absolute_import, print_function

import codecs
import sys
import zlib
from StringIO import StringIO
from PIL import Image
from zipfile import ZipFile
from xml.dom import minidom
import xml.dom
from optparse import OptionParser, OptionGroup


class Style(object):
  def __init__(self, bold, italic, underline):
    self.bold = bold
    self.italic = italic
    self.underline = underline

if __name__ == "__main__":
  # replace stderr and stdout with a utf-8 encoding StreamWriter, so that it can output non-ASCII characters
  sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
  sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

  usage = "%prog [-d <image_dir>] <infile.snb>"
  parser = OptionParser(usage=usage)
  parser.add_option("-d", "--dir", dest="image_dir", help="Extract images to <image_dir>", metavar="<image_dir>")
  parser.add_option_group(OptionGroup(parser, "Operation", "Reads a Samsung S-Note file <infile.snb> and converts it to text in markdown syntax. The result is written to stdout."))
  (options, args) = parser.parse_args()
  if args:
    options.file = args[0]
  else:
    parser.print_help(sys.stderr)
    sys.exit(1)

  charStyle = dict()
  rels = dict()
  imgpath = ""
  include_backgrounds = False
  infile = options.file
  extract_images = (options.image_dir is not None)
  if extract_images: imgpath = options.image_dir
  if imgpath != "" and not imgpath.endswith("/"): imgpath += "/"
  
  zipfl = ZipFile(infile, "r")
  
  sty = zipfl.open("snote/styles.xml")
  styles = minidom.parseString(sty.read())
  for style in styles.getElementsByTagName("sn:style"):
    if style.getAttributeNode("sn:type").value == "character":
      charStyleId = style.getAttributeNode("sn:styleId").value
      charStyle[charStyleId] = Style(len(style.getElementsByTagName("sn:b"))>0, len(style.getElementsByTagName("sn:i"))>0, len(style.getElementsByTagName("sn:u"))>0)
  sty.close()
  
  rel = zipfl.open("snote/_rels/snote.xml.rels")
  relations = minidom.parseString(rel.read())
  for relation in relations.getElementsByTagName("Relationship"):
    relId = relation.getAttribute("Id")
    target = relation.getAttribute("Target")
    rels[relId] = target
  rel.close()
    
  notexml = zipfl.open("snote/snote.xml")
  note = minidom.parseString(notexml.read())
  
  node = note.documentElement
  while True:
    if node.firstChild is not None:
      node = node.firstChild
    elif node.nextSibling is not None:
      node = node.nextSibling
    else:
      while True:
        node = node.parentNode
        if node.nodeType == xml.dom.Node.DOCUMENT_NODE: sys.exit(0)
        if node.nextSibling is None: continue
        node = node.nextSibling
        break
    
    if node.nodeType != xml.dom.Node.ELEMENT_NODE: continue
  
    block = node
    if block.tagName == "v:imagedata":
      is_background = block.parentNode.parentNode.parentNode.getAttribute("sn:insertimagetype") == "1"
      imgrelpath = rels[block.getAttribute("r:id")]
      imgname = imgrelpath.rsplit("/",1)[1]
      if include_backgrounds or not is_background:
        imgfile = zipfl.open("snote/"+imgrelpath)
        imgdata = imgfile.read()
        imgfile.close()
        if imgname.endswith(".zdib"):
          imgdata = zlib.decompress(imgdata)
          imgname = imgname.rsplit(".",1)[0]+".png"
          width = ord(imgdata[5]) * 256 + ord(imgdata[4])
          height = ord(imgdata[9]) * 256 + ord(imgdata[8])
          imgdata = imgdata[52:]
          img = Image.fromstring("RGBA",(width,height),imgdata)
          sio = StringIO()
          img.save(sio, "PNG")
          imgdata = sio.getvalue()
          sio.close()
        
        sys.stdout.write("\n![%s](%s)\n\n" % (imgname, imgpath+imgname))
        
        if extract_images:
          imgout = open(imgpath+imgname,"wb")
          imgout.write(imgdata)
          imgout.close()
    
    if block.tagName == "sn:l":
      for run in block.getElementsByTagName("sn:r"):
        surround = ""
        if len(run.getElementsByTagName("sn:t")) > 0:
          charStyleId = "Character" + run.getAttributeNode("sn:rStyle").value
          if charStyle[charStyleId].bold: 
            surround = "**"
            sys.stdout.write(surround)
          else:
            if charStyle[charStyleId].italic or charStyle[charStyleId].underline: 
              surround = "_"
              sys.stdout.write(surround)
        
        for bullet in run.getElementsByTagName("sn:bulletText"):
          if bullet.firstChild.data == "l":
            sys.stdout.write("* ")
          elif bullet.firstChild.data == "u":
            sys.stdout.write("    - ")
          elif bullet.firstChild.data[0].isdigit():
            #sys.stdout.write(bullet.firstChild.data)
            sys.stdout.write("1. ")
          else:
            sys.stdout.write("        + ")
        
        for text in run.getElementsByTagName("sn:t"):
          for t in text.childNodes:
            if t.nodeType == xml.dom.Node.TEXT_NODE:
              sys.stdout.write(t.data)
        
        sys.stdout.write(surround)

        if len(run.getElementsByTagName("sn:paraend"))+len(run.getElementsByTagName("sn:br")) > 0:
          sys.stdout.write("\n")
      sys.stdout.write("\n")
      